<template>
	<div class="searchBox" ref="searchBox">
		<el-form :inline="true" size="mini" :model="searchForm" ref="searchForm" id="searchFormFd" :rules="rules" label-width="70px">
			<el-form-item label="所属组织" prop="org_id">
				<TreeSelect :data="orgTreeDatas" :value="searchForm.org_id" :multiple="true" :expandKeys="expandKeys" width="180px" :filterable="true" @treeSelectChange="treeSelectChange" />
			</el-form-item>
			<el-form-item label="所属模块" prop="fault_type">
				<el-select v-model="searchForm.fault_type" style="width: 180px" multiple filterable collapse-tags clearable placeholder="请选择">
					<el-option v-for="(item,id) in faultTypeOptions" :key="id" :label="item.name" :value="item.value"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="时间范围" prop="timeFrame">
				<el-date-picker v-model="searchForm.timeFrame" :type="pickerType" :format="format" :value-format="valueFormat" align="right" unlink-panels range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
				</el-date-picker>
			</el-form-item>
			<el-form-item label="设备型号" prop="vehicle_model">
				<el-select v-model="searchForm.vehicle_model" style="width: 180px" placeholder="请选择" clearable filterable @change="modelChange">
					<el-option v-for="item in modelOptions" :key="item.id" :label="item.modelName" :value="`${item.id}_${item.modelName}`">
					</el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="设备编号" prop="vehicle_number">
				<el-select v-model="searchForm.vehicle_number" style="width: 180px" multiple collapse-tags filterable clearable placeholder="请选择" @change="changeNumber">
					<div class="selectAll"><el-checkbox v-model="checked" @change="selectAll">全选</el-checkbox></div>
					<el-option v-for="item in numberOptions" :key="item.id" :label="item.vehicleNo" :value="item.vin">
					</el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="故障名称" prop="fault_name">
				<el-input v-model="searchForm.fault_name" placeholder="请输入故障名称" clearable></el-input>
			</el-form-item>
			<el-form-item label="故障等级" prop="fault_level">
				<el-select v-model="searchForm.fault_level" style="width: 180px" multiple filterable collapse-tags clearable placeholder="请选择">
					<el-option v-for="(item,id) in faultLevalOptions" :key="id" :label="item.name" :value="item.value"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="生产模式" prop="product_mode">
				<el-select v-model="searchForm.product_mode" style="width: 180px" filterable clearable placeholder="请选择">
					<el-option v-for="item in productModeOptions" :key="item.value" :label="item.label" :value="item.value">
					</el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="程序版本" prop="versions">
				<el-select v-model="searchForm.versions" style="width: 180px" multiple filterable collapse-tags clearable placeholder="请选择">
					<el-option v-for="item in programVersionOptions" :key="item.value" :label="item.label" :value="item.value">
					</el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="驾驶模式" prop="driver_mode">
				<el-select v-model="searchForm.driver_mode" style="width: 180px" multiple filterable collapse-tags clearable placeholder="请选择">
					<el-option v-for="item in driveModeOptions" :key="item.value" :label="item.label" :value="item.value">
					</el-option>
				</el-select>
			</el-form-item>
			<el-form-item class="btnBox">
				<span class="searchBtn" :class="{'forbidBtn':loading}" @click="validateSearchForm('searchForm', 'search')">查询</span>
				<span class="resetBtn" @click="resetForm()">重置</span>
			</el-form-item>
		</el-form>
	</div>
</template>

<script>
import server from "@/server/index";
import TreeSelect from "@/components/TreeSelect";
import { getItem } from "@/utils";
import { getYesterday, getCurYearMonth, getDayPickOptions, getMonthPickOptions } from '@/utils/dateUtils';

export default {
	name: 'globalSearch',
	components: {
		TreeSelect
	},
	props: {
		type: {
			type: String,
			default: 'global'
		},
		coreLoading: {
			type: Boolean,
			default: false
		},
		specialLoading: {
			type: Boolean,
			default: false
		},
		multiLoading: {
			type: Boolean,
			default: false
		}
	},
	data() {
		let _this = this;
		return {
			checked: false,
			searchForm: {
				timeFrame: [getYesterday(), getYesterday()],
				vehicle_model: "",
				vehicle_number: [],
				fault_level: [],
				fault_type: [],
				driver_mode: [],
				product_mode: '',
				versions: [],
				org_id: "",
				fault_name: ""
			},
			// 故障类型options
			faultTypeOptions: [],
			// 故障级别options
			faultLevalOptions: [],
			// 设备编号options
			numberOptions: [],
			// 设备型号options
			modelOptions: [],
			// 程序版本options
			programVersionOptions: [],
			// 生产模式options
			productModeOptions: [],
			// 驾驶模式options
			driveModeOptions: [],
			pickerType: "daterange",
			orgTreeDatas: getItem('orgTreeDatas'),
			expandKeys: [],
			expandKeys: [],
			format: 'yyyy-MM-dd',
			valueFormat: "yyyy-MM-dd",
			rules: {
				org_id: [
					{
						required: true,
						message: "请选择所属组织",
						trigger: "change",
					},
				],
				timeFrame: [
					{
						required: true,
						message: "选择时间范围",
						trigger: "change",
					},
				]
			},
		}
	},
	computed: {
		loading() {
			if (this.type === 'global') {
				return (this.coreLoading && this.specialLoading);
			}
			if (this.type === 'local') {
				return this.multiLoading;
			}
		}
	},
	mounted() {
		// this.getDefaultCheckedKeys();
		// this.validateSearchForm('searchForm', 'search');
		this.init();
	},
	methods: {
		init(){
	        this.$nextTick(() => {
    			this.treeSelectChange({ nodes: getItem('defaultNodes'), keys: getItem('defaultOrgIds') });
    		});
	    },
		treeSelectChange({ nodes, keys }) {
			const org_id = keys.join(",");

			if (this.searchForm.org_id !== org_id || org_id === "") {
				this.searchForm.vehicle_model = "";
				this.searchForm.vehicle_number = [];
				this.searchForm.org_id = org_id;

				this.searchForm.versions = [];
				this.getModelOptions();
				this.getNumberOptions();
				this.getFaultTypeOptions();
				this.getFaultLevelOptions();
				this.getPropramVersionOptions();
				this.getDriveModeOptions();
				this.getProductModeOptions();

				const id = nodes[0] ? nodes[0].id : "";
				this.setTreeDataDisable(id, keys);
			}
		},
		setTreeDataDisable(id = "", keys) {
			let orgTreeDatas = JSON.parse(JSON.stringify(this.orgTreeDatas));
			const recusive = (datas, bool) => {
				datas.forEach((data) => {
					data.disabled = bool;
					if (data.children.length) {
						recusive(data.children, bool);
					}
				});
			};

			recusive(orgTreeDatas, false);

			if (id) {
				orgTreeDatas.forEach((data) => {
					if (data.id !== id) {
						data.disabled = true;
						if (data.children.length) {
							recusive(data.children, true);
						}
					}
				});
			}

			this.orgTreeDatas = orgTreeDatas;
			if (keys.length > 0) {
				this.expandKeys = keys;
			}
		},
		// 获取故障类型options
		getFaultTypeOptions() {
			const params = {
				equal: {
					orgId: this.searchForm.org_id,
					type: '2'
				}
			};

			server.technical.getFaultType(params)
				.then(res => {
					const { code, data } = res;
					if (code === '200') {
						this.faultTypeOptions = data;
					} else {
						this.faultTypeOptions = [];
					}
				})
		},
		// 获取故障级别options
		getFaultLevelOptions() {
			const params = {
				equal: {
					orgId: this.searchForm.org_id,
					type: '1'
				}
			};

			server.technical.getFaultLeval(params)
				.then(res => {
					const { code, data } = res;
					if (code === '200') {
						this.faultLevalOptions = data;
					} else {
						this.faultLevalOptions = [];
					}
				})
		},
		// 获取设备型号options
		getModelOptions() {
			const params = {
				like: {
					orgId: this.searchForm.org_id,
				},
				equal: {
					vehicleCategory: '1'
				}
			};
			server.deviceManage.getModelList(params)
				.then(res => {
					const { code, data } = res;
					if (code === "200" && data.length) {
						this.modelOptions = data;
					} else {
						this.modelOptions = [];
					}
				})
		},
		// 获取设备编号options
		getNumberOptions() {
			this.checked = false;
			const { vehicle_model } = this.searchForm;
			let equal = {
				vehicleCategory: '1',
			};

			if (vehicle_model) {
				equal.modelId = vehicle_model.split('_')[0];
			}

			const params = {
				like: {
					orgId: this.searchForm.org_id,
				},
				equal
			};

			server.deviceManage.getNumberList(params)
				.then(res => {
					let { code, data } = res;
					data = data ? data : [];
					if (code === "200" && data.length) {
						this.numberOptions = data;
					} else {
						this.numberOptions = [];
					}
				})
		},
		// 获取程序版本options
		getPropramVersionOptions() {
			const params = {
				equal: {
					code: 'sys_process_version_type',
					orgId: this.searchForm.org_id,
				}
			};

			server.technical.getProgramVersions(params)
				.then(res => {
					const { code, data } = res;
					if (code === '200') {
						this.programVersionOptions = data;
					} else {
						this.programVersionOptions = [];
					}
				});
		},
		// 获取驾驶模式options
		getDriveModeOptions() {
			const params = {
				equal: {
					code: 'sys_driver_mode',
					orgId: this.searchForm.org_id,
				}
			};

			server.technical.queryDicItemsByTypeCode(params)
				.then(res => {
					const { code, data } = res;
					if (code === '200') {
						this.driveModeOptions = data;
					} else {
						this.driveModeOptions = [];
					}
				});
		},
		// 获取生产模式options
		getProductModeOptions() {
			const params = {
				equal: {
					code: 'sys_product_mode',
					orgId: this.searchForm.org_id,
				}
			};

			server.technical.queryDicItemsByTypeCode(params)
				.then(res => {
					const { code, data } = res;
					if (code === '200') {
						this.productModeOptions = data;
					} else {
						this.productModeOptions = [];
					}
				});
		},
		// 设备型号切换事件
		modelChange() {
			this.getNumberOptions();
			this.searchForm.vehicle_number = [];
		},
		changeNumber(val) {
			if (val.length === this.numberOptions.length) {
				this.checked = true;
			} else {
				this.checked = false;
			}
		},
		selectAll() {
			this.searchForm.vehicle_number = [];
			if (this.checked) {
				this.numberOptions.forEach((item) => { this.searchForm.vehicle_number.push(item.vin) });
			}
		},
		//表单验证
		validateSearchForm(formName, type) {
			if (this.loading) return;
			this.$refs[formName].validate((valid) => {
				if (valid) {
					this.handleSearch();
				} else {
					return false;
				}
			});
		},
		getParams() {
			let params = {};
			let selectArr = ['vehicle_number', 'fault_level', 'fault_type', 'driver_mode', 'versions']

			Object.keys(this.searchForm).forEach(key => {
				if (selectArr.includes(key)) {
					params[key] = this.searchForm[key].join(',');
				} else {
					if (key === 'vehicle_model' && this.searchForm[key]) {
						params[key] = this.searchForm[key].split('_')[1]
					} else {
						params[key] = this.searchForm[key];
					}
				}
			});
			return params;
		},
		// 搜索
		handleSearch() {
			if (new Date(`${this.searchForm.timeFrame[1]} 23:59:59`) - new Date(`${this.searchForm.timeFrame[0]} 00:00:00`) > 7 * 24 * 60 * 60 * 1000) {
				this.$message({
					type: 'warning',
					message: '查询范围不能超过7天!'
				});
				return;
			}

			const params = this.getParams();
			this.$emit('handleSearch', { type: this.type, params });
		},
		// 重置
		resetForm() {
			this.searchForm = {
				timeFrame: [getYesterday(), getYesterday()],
				vehicle_model: "",
				vehicle_number: [],
				fault_level: [],
				fault_type: [],
				driver_mode: [],
				product_mode: '',
				versions: [],
				org_id: "",
				fault_name: ""
			};
			this.$emit('handleSearch', { type: this.type, params: {} });
			this.init();
		},
		// 获取默认选中组织
		getDefaultCheckedKeys() {
			const checkedKeys = [];
			const recusive = (datas) => {
				datas.forEach(data => {
					if (data.children.length === 0) {
						checkedKeys.push(data.id);
					} else {
						recusive(data.children);
					}

				});
			};
			recusive(this.orgTreeDatas);
			this.searchForm.org_id = checkedKeys.join(',');
		}
	},
}
</script>

<style lang="scss" scoped>
// .btnBox {
// 	padding-left: 10px;
// }
</style>